package serverService;

import common.Message;
import common.MessageType;
import utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;

/**
 * @author lhn
 * @date 2024-05-16 16:08
 */

public class SendNewsToAllService implements Runnable{

    @Override
    public void run() {
        //为了推送多次新闻,使用while
        while (true) {
            System.out.println("请输入要推送的新闻/消息[输入exit退出推送服务]:");
            String news = Utility.readString(100);
            if ("exit".equals(news)) {
                break;
            }
            Message message = new Message();
            message.setContent(news);
            message.setSender("服务器");
            message.setSendTime(new Date().toString());
            message.setMesType(MessageType.MESSAGE_COMMON_MESSAGE_ALL);
            System.out.println("服务器推送消息给所有人,对所有人说：" + news);

            HashMap<String, ServerConnectClientThread> hashMap = ManageServerConnectClientThread.getHashMap();
            for (String key: hashMap.keySet()
            ) {
                ServerConnectClientThread serverConnectClientThread = hashMap.get(key);
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());
                    objectOutputStream.writeObject(message);

                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                }
            }
        }


    }
}
